package com.ztorn.fiscale.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ztorn.common.core.web.controller.BaseController;
import com.ztorn.common.core.web.page.TableDataInfo;
import com.ztorn.common.core.web.domain.AjaxResult;

import com.ztorn.fiscale.domain.FiscaleTaxInvoice;
import com.ztorn.fiscale.domain.FiscaleTaxInvoiceItem;
import com.ztorn.fiscale.domain.FiscaleTaxDeclarationRelation;
import com.ztorn.fiscale.domain.FiscaleCustomsDeclaration;
import com.ztorn.fiscale.service.IFiscaleTaxInvoiceService;
import com.ztorn.fiscale.service.IFiscaleTaxInvoiceItemService;
import com.ztorn.fiscale.service.IFiscaleTaxDeclarationRelationService;
import com.ztorn.fiscale.service.IFiscaleCustomsDeclarationService;

/**
 * 税务管理Controller
 *
 * @author ztorn
 * @date 2025-09-19
 */
@RestController
@RequestMapping("/tax")
public class TaxManagementController extends BaseController
{
    @Autowired
    private IFiscaleTaxInvoiceService fiscaleTaxInvoiceService;

    @Autowired
    private IFiscaleTaxInvoiceItemService fiscaleTaxInvoiceItemService;

    @Autowired
    private IFiscaleTaxDeclarationRelationService fiscaleTaxDeclarationRelationService;

    @Autowired
    private IFiscaleCustomsDeclarationService fiscaleCustomsDeclarationService;

    /**
     * 查询待开票报关单列表（已放行或已结关且未关联发票的报关单）
     */
    @GetMapping("/pendingInvoices")
    public TableDataInfo listPendingInvoices()
    {
        // 查询所有已放行或已结关的报关单
        FiscaleCustomsDeclaration query = new FiscaleCustomsDeclaration();
        List<FiscaleCustomsDeclaration> allDeclarations = fiscaleCustomsDeclarationService.selectFiscaleCustomsDeclarationList(query);

        // 筛选出已放行(状态为"已放行"或"已结关")且未关联发票的报关单
        List<FiscaleCustomsDeclaration> pendingInvoices = allDeclarations.stream()
            .filter(declaration ->
                ("已放行".equals(declaration.getCustomsStatus()) || "已结关".equals(declaration.getCustomsStatus())) &&
                fiscaleTaxDeclarationRelationService.selectFiscaleTaxDeclarationRelationByDeclarationId(declaration.getDeclarationId()) == null
            )
            .collect(Collectors.toList());

        return getDataTable(pendingInvoices);
    }

    /**
     * 根据报关单ID列表获取待开票详情
     */
    @PostMapping("/pendingInvoices/details")
    public AjaxResult getPendingInvoiceDetails(@RequestBody List<Long> declarationIds)
    {
        try {
            List<FiscaleCustomsDeclaration> declarations = new ArrayList<>();
            for (Long declarationId : declarationIds) {
                FiscaleCustomsDeclaration declaration = fiscaleCustomsDeclarationService.selectFiscaleCustomsDeclarationByDeclarationId(declarationId);
                if (declaration != null) {
                    declarations.add(declaration);
                }
            }

            return AjaxResult.success(declarations);
        } catch (Exception e) {
            return AjaxResult.error("获取报关单详情失败：" + e.getMessage());
        }
    }

    /**
     * 预览发票
     */
    @PostMapping("/previewInvoice")
    public AjaxResult previewInvoice(@RequestBody FiscaleTaxInvoice invoice)
    {
        try {
            // 这里应该生成发票预览数据
            // 实际实现中可能需要调用PDF生成服务
            return AjaxResult.success("发票预览数据生成成功", invoice);
        } catch (Exception e) {
            return AjaxResult.error("生成发票预览失败：" + e.getMessage());
        }
    }

    /**
     * 开具发票
     */
    @PostMapping("/issueInvoice")
    public AjaxResult issueInvoice(@RequestBody FiscaleTaxInvoice invoice)
    {
        try {
            // 1. 保存发票主表
            fiscaleTaxInvoiceService.insertFiscaleTaxInvoice(invoice);

            // 获取生成的发票ID
            Long invoiceId = invoice.getInvoiceId();

            // 2. 保存发票明细
            if (invoice.getInvoiceItems() != null && !invoice.getInvoiceItems().isEmpty()) {
                for (FiscaleTaxInvoiceItem item : invoice.getInvoiceItems()) {
                    item.setInvoiceId(invoiceId);
                }
                fiscaleTaxInvoiceItemService.insertFiscaleTaxInvoiceItems(invoice.getInvoiceItems());
            }

            // 3. 保存报关单与发票关联关系
            if (invoice.getDeclarationIds() != null && !invoice.getDeclarationIds().isEmpty()) {
                List<FiscaleTaxDeclarationRelation> relations = new ArrayList<>();
                for (Long declarationId : invoice.getDeclarationIds()) {
                    FiscaleTaxDeclarationRelation relation = new FiscaleTaxDeclarationRelation();
                    relation.setDeclarationId(declarationId);
                    relation.setInvoiceId(invoiceId);
                    relations.add(relation);
                }
                fiscaleTaxDeclarationRelationService.insertFiscaleTaxDeclarationRelations(relations);

                // 4. 更新报关单状态为"已开票"
                for (Long declarationId : invoice.getDeclarationIds()) {
                    FiscaleCustomsDeclaration declaration = fiscaleCustomsDeclarationService.selectFiscaleCustomsDeclarationByDeclarationId(declarationId);
                    if (declaration != null) {
                        declaration.setCustomsStatus("已开票");
                        fiscaleCustomsDeclarationService.updateFiscaleCustomsDeclaration(declaration);
                    }
                }
            }

            // 5. 模拟调用税务UKey服务或云端税务接口
            // 实际实现中需要调用真实的税务接口
            String invoiceCode = "12345678"; // 发票代码
            String invoiceNumber = "98765432"; // 发票号码

            // 6. 更新发票信息
            invoice.setInvoiceCode(invoiceCode);
            invoice.setInvoiceNumber(invoiceNumber);
            invoice.setStatus("已开具");
            fiscaleTaxInvoiceService.updateFiscaleTaxInvoice(invoice);

            return AjaxResult.success("开票成功", invoice);
        } catch (Exception e) {
            return AjaxResult.error("开票失败：" + e.getMessage());
        }
    }

    /**
     * 下载发票
     */
    @GetMapping("/downloadInvoice/{invoiceId}")
    public AjaxResult downloadInvoice(@PathVariable Long invoiceId)
    {
        try {
            FiscaleTaxInvoice invoice = fiscaleTaxInvoiceService.selectFiscaleTaxInvoiceById(invoiceId);
            if (invoice == null) {
                return AjaxResult.error("发票不存在");
            }

            // 实际实现中应该返回发票PDF文件
            // 这里只是模拟返回发票信息
            return AjaxResult.success("发票下载链接生成成功", invoice);
        } catch (Exception e) {
            return AjaxResult.error("生成发票下载链接失败：" + e.getMessage());
        }
    }

    /**
     * 查询已开发票列表
     */
    @GetMapping("/issuedInvoices")
    public TableDataInfo listIssuedInvoices(FiscaleTaxInvoice invoice)
    {
        startPage();
        List<FiscaleTaxInvoice> list = fiscaleTaxInvoiceService.selectFiscaleTaxInvoiceList(invoice);
        return getDataTable(list);
    }

    /**
     * 获取已开发票详细信息
     */
    @GetMapping("/issuedInvoices/{invoiceId}")
    public AjaxResult getIssuedInvoice(@PathVariable Long invoiceId)
    {
        FiscaleTaxInvoice invoice = fiscaleTaxInvoiceService.selectFiscaleTaxInvoiceById(invoiceId);
        if (invoice == null) {
            return AjaxResult.error("发票不存在");
        }

        // 获取发票明细
        List<FiscaleTaxInvoiceItem> items = fiscaleTaxInvoiceItemService.selectFiscaleTaxInvoiceItemByInvoiceId(invoiceId);
        invoice.setInvoiceItems(items);

        // 获取关联的报关单信息
        List<FiscaleTaxDeclarationRelation> relations = fiscaleTaxDeclarationRelationService.selectFiscaleTaxDeclarationRelationByInvoiceId(invoiceId);
        if (relations != null && !relations.isEmpty()) {
            List<Long> declarationIds = new ArrayList<>();
            for (FiscaleTaxDeclarationRelation relation : relations) {
                declarationIds.add(relation.getDeclarationId());
            }
            invoice.setDeclarationIds(declarationIds);
        }

        return AjaxResult.success(invoice);
    }

    /**
     * 撤销发票
     */
    @PutMapping("/revokeInvoice/{invoiceId}")
    public AjaxResult revokeInvoice(@PathVariable Long invoiceId)
    {
        try {
            FiscaleTaxInvoice invoice = fiscaleTaxInvoiceService.selectFiscaleTaxInvoiceById(invoiceId);
            if (invoice == null) {
                return AjaxResult.error("发票不存在");
            }

            // 只有已开具状态的发票才能撤销
            if (!"已开具".equals(invoice.getStatus())) {
                return AjaxResult.error("只有已开具状态的发票才能撤销");
            }

            // 更新发票状态为已撤销
            int result = fiscaleTaxInvoiceService.revokeFiscaleTaxInvoice(invoiceId);

            // 如果需要，可以在这里添加其他业务逻辑，比如更新关联报关单的状态等

            return AjaxResult.success("发票撤销成功");
        } catch (Exception e) {
            return AjaxResult.error("发票撤销失败：" + e.getMessage());
        }
    }

    /**
     * 重新开具发票
     */
    @PutMapping("/reissueInvoice/{invoiceId}")
    public AjaxResult reissueInvoice(@PathVariable Long invoiceId)
    {
        try {
            FiscaleTaxInvoice invoice = fiscaleTaxInvoiceService.selectFiscaleTaxInvoiceById(invoiceId);
            if (invoice == null) {
                return AjaxResult.error("发票不存在");
            }

            // 只有已撤销状态的发票才能重新开具
            if (!"已撤销".equals(invoice.getStatus())) {
                return AjaxResult.error("只有已撤销状态的发票才能重新开具");
            }

            // 更新发票状态为已开具
            int result = fiscaleTaxInvoiceService.reissueFiscaleTaxInvoice(invoiceId);

            return AjaxResult.success("发票重新开具成功");
        } catch (Exception e) {
            return AjaxResult.error("发票重新开具失败：" + e.getMessage());
        }
    }
}
